/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.travelFinder.service;

import com.travelFinder.controller.ConnectionController.InputFileEntry;
import com.travelFinder.domain.Connection;
import com.travelFinder.domain.Place;
import com.travelFinder.domain.utils.Weekdays;
import com.travelFinder.repository.ConnectionRepository;
import com.travelFinder.repository.PlaceRepository;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Kryl
 */
@Service
public class DbPopulator {

    @Autowired
    PlaceRepository placeRepository;
    @Autowired
    ConnectionRepository connectionRepository;

    @Transactional
    public String populateDatabase(List<InputFileEntry> csvFiles) {
        connectionRepository.deleteAll();
        placeRepository.deleteAll();

        for (InputFileEntry file : csvFiles) {

            try {
                try {
                    parse(file);
                } catch (ParseException ex) {
                    Logger.getLogger(DbPopulator.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (IOException ex) {
                Logger.getLogger(DbPopulator.class.getName()).log(Level.SEVERE, null, ex);
            }
            Logger.getLogger(DbPopulator.class.getName()).log(Level.INFO, " file done: " + file.getFile().getAbsolutePath());
        }


        return "";
    }

    private void parse(InputFileEntry entry) throws IOException, ParseException {
        File csvFile = entry.getFile();
        
        BufferedReader fr =new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), "UTF-8"));
        int id = -1;
        String line;
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        while ((line = fr.readLine()) != null) {
            //sample line Tczew*Miłobądz*05:54*06:00*01.01*31.12*Pt-Sb*0
            String[] connectionData = line.split("\\*");
            String start = connectionData[0];
            String end = connectionData[1];
            Integer departureTime = timeFromString(connectionData[2]);
            Integer arrivalTime = timeFromString(connectionData[3]);
            Date startDate = sdf.parse(connectionData[4] + ".2012");
            Date endDate = sdf.parse(connectionData[5] + ".2012");
            Weekdays days = Weekdays.parseString(connectionData[6]);
            Boolean[] days2 = Weekdays.parseString2(connectionData[6]);
            String connectionId = connectionData[7];

            Place startPlace = placeRepository.findByPropertyValue("name", start);
            if (startPlace == null) {
                startPlace = new Place(start);
                placeRepository.save(startPlace);
                startPlace = placeRepository.findByPropertyValue("name", start);
            }

            Place endPlace = placeRepository.findByPropertyValue("name", end);
            if (endPlace == null) {
                endPlace = new Place(end);
                placeRepository.save(endPlace);
                endPlace = placeRepository.findByPropertyValue("name", end);

            }

            Connection connection = new Connection(startPlace, endPlace);
            startPlace.addConnection(connection);

            connection.setStartTime(departureTime);
            if (arrivalTime < departureTime) {
                connection.setDuration(1440 - departureTime + arrivalTime);
            } else {
                connection.setDuration(arrivalTime - departureTime);
            }
            connection.setCompany(entry.getCompany());
            connection.setType(entry.getType());
            connection.setEndDate(new Date(arrivalTime));
            connection.setStartDate(new Date(departureTime));
            connection.setConnectionId(connectionId);
            connection.setStartDate(startDate);
            connection.setEndDate(endDate);
            connection.setWeekdaysActive(days);
            connection.setWeekdaysActive2(days2);
            connectionRepository.save(connection); //NIE ZAPOMINAĆ O TYM!!

            // 
        }
    }

    Integer timeFromString(String s) {
        String[] t = s.split("\\:");
        return Integer.parseInt(t[0]) * 60 + Integer.parseInt(t[1]);
    }
}